#include <stdio.h>
#include <stdlib.h>
#include <expat.h>
#include <unistd.h>
#include <glib.h>
#include "parser.h"
#include "generater.h"

typedef enum LogType {
    LT_SANDBOX,
    LT_WINPORCMON,
    LT_ERR = -1
} LogType;

static LogType
get_log_type (const char type[]) {
    if (!strcmp (type, "sandbox")) {
        return LT_SANDBOX; 
    }
    if (!strcmp (type, "winprocmon")) {
        return LT_WINPORCMON; 
    }
    return LT_ERR;
}


static void
simple_elem_reader (LogElem *el) {
    print_log_elem_type (el->type);
    printf (" %s", el->src);
    print_log_elem_point_type (el->src_type);
    printf ("->%s", el->dest);
    print_log_elem_point_type (el->dest_type);
    printf ("\n");
}

int
main (const int argc, const char *argv[]) {
    LogType log_type;
    LogParser *parser;
    LogElem *elem;
    GraphGenerater *gen;
    int stat;
    int log_fd;
    if (argc != 2) {
        printf ("usage: %s type\n", argv[0]);
        goto out;
    }
    log_fd = STDIN_FILENO;
    log_type = get_log_type (argv[1]);
    if (log_type == LT_ERR) {
        printf ("Unknown log type.\n");
        goto out;
    }

    switch (log_type)
    {
    case LT_SANDBOX:
        stat = sandbox_log_parser_create (&parser, stdin); 
        break;
    case LT_WINPORCMON:
        stat = winprocmon_log_parser_create (&parser, stdin); 
        break;
    default:
        printf ("Unsupported log type.\n");
        goto out;
        break;
    }

    if (stat != 0) {
        printf ("Unable to create log parser.\n");
        goto fail;
    }

    if (default_graph_generater_create (&gen) != 0) {
         printf ("Unable to create graph generater.\n");
        goto fail;
    }

    stat = creat_log_elem (&elem);
    if (stat != 0) {
        printf ("Unable to create elem buffer.\n");
        goto fail;
    }
    while ((stat = parse_log (parser, elem)) == PARSE_LOG_INCOMING) {
        process_log (gen, elem);
        clean_log_elem (elem);
        //exit (0);
    }
    (void) free_log_elem (elem);
    
    if (stat == PARSE_LOG_ERR) {
        printf ("Parse error.\n");
        goto fail;
    }
    graph_gernerate (gen, stdout);

    out:
    exit (EXIT_SUCCESS);
    fail:
    exit (EXIT_FAILURE);
}